<?php
ini_set('memory_limit', '-1');
set_time_limit(1200);

mysql_connect("dev.ivaldi.nl", "root", "w8woord-ivaldi") or die(mysql_error());
mysql_select_db("publicationsv2") or die(mysql_error());

//grab the sameas file
function parse_sames(){
	$lines = file('/home/bas/public_html/sameas.n3');

	// Loop through our array, fix the URIs and add them to the db
	foreach ($lines as $line_num => $line) {
		$arr = preg_split('/(<)/', $line);
		array_shift($arr);	
		$i = 0;
		foreach($arr as $line_num){
			$arr[$i] = htmlspecialchars($line_num);	
			$arr[$i] = str_replace('&gt;','',$arr[$i]);
			$arr[$i] = str_replace(' .','',$arr[$i]);
			$i++;
		}
		mysql_query("INSERT INTO authors_sameas (id, subject, predicate, object) VALUES ('', '".$arr[0]."', '".$arr[1]."', '".$arr[2]."' )");
	}

	//trim the results
	$res = mysql_query("SELECT * FROM authors_sameas");
	while($row = mysql_fetch_array($res)){
		$id = $row['id'];
		$s = trim($row['subject']);
		$p = trim($row['predicate']);
		$o = trim($row['object']);
		mysql_query("UPDATE authors_sameas SET subject = '".$s."', predicate = '".$p."', object = '".$o."' WHERE id = '".$id."'");
	}
}

//this function denormalizes the authors, based on the 'and' delimiter
function denormalize(){
	$tables = array('book', 'booklet', 'inbook', 'incollection', 'mastersthesis', 'misc', 'phdthesis', 'techreport', 'inproceedings');
	foreach($tables as $table) {

		$query = mysql_query("SELECT author,entry_id FROM ".$table);
		while ($row = mysql_fetch_assoc($query)) {
			//echo $row['author'];
			//$author = str_replace(' ','',$row['author']);
			$authors = split(' and ', $row['author']);
			foreach ($authors as $value){
				if($value != ''){
					mysql_query("INSERT INTO authors_dn (id, name, entry_id) VALUES ('', '".$value."', '".$row['entry_id']."')");		
				}
			}
		}
	}
}

function my_in_array($needle,$haystack) 
{
	if (sizeof($haystack) > 0)
	{
		return in_array($needle, $haystack);
	}
	return false;	
}

//bundle the authors together and return bundles array
function bundle_authors(){
	$sub_array[] = '0';
	$authors[] = array();

	$i = -1;

	$res = mysql_query("SELECT DISTINCT subject, object FROM authors_sameas");
	while($row = mysql_fetch_array($res)){
		if(!my_in_array($row['subject'],$all)){
			$i++;
			
			$authors[$i][] = $row['subject'];
			$authors[$i][] = $row['object'];
			$all[] = $row['subject'];
			$all[] = $row['object'];
			
			foreach($authors[$i] as $author){
				$query = mysql_query("SELECT DISTINCT subject, object FROM authors_sameas WHERE object = '".$author."'");
				while($roww = mysql_fetch_array($query)){
					$s = $roww['subject'];
					$o = $roww['object'];
					
					if(!my_in_array($s,$authors[$i])){
						$authors[$i][] = $s;
						$all[] = $s;
					}
					if(!my_in_array($o,$authors[$i])){
						$authors[$i][] = $o;
						$all[] = $o;
					}
				}
			}
			
			foreach($authors[$i] as $author){
				$query = mysql_query("SELECT DISTINCT subject, object FROM authors_sameas WHERE subject = '".$author."'");
				while($rowww = mysql_fetch_array($query)){
					$s = $rowww['subject'];
					$o = $rowww['object'];
					
					if(!my_in_array($s,$authors[$i])){
						$authors[$i][] = $s;
						$all[] = $s;
					}
					if(!my_in_array($o,$authors[$i])){
						$authors[$i][] = $o;
						$all[] = $o;
					}
				}
			}		
			
			foreach($authors[$i] as $author){
				$query = mysql_query("SELECT DISTINCT subject, object FROM authors_sameas WHERE object = '".$author."'");
				while($roww = mysql_fetch_array($query)){
					$s = $roww['subject'];
					$o = $roww['object'];
					
					if(!my_in_array($s,$authors[$i])){
						$authors[$i][] = $s;
						$all[] = $s;
					}
					if(!my_in_array($o,$authors[$i])){
						$authors[$i][] = $o;
						$all[] = $o;
					}
				}
			}
			
			foreach($authors[$i] as $author){
				$query = mysql_query("SELECT DISTINCT subject, object FROM authors_sameas WHERE subject = '".$author."'");
				while($rowww = mysql_fetch_array($query)){
					$s = $rowww['subject'];
					$o = $rowww['object'];
					
					if(!my_in_array($s,$authors[$i])){
						$authors[$i][] = $s;
						$all[] = $s;
					}
					if(!my_in_array($o,$authors[$i])){
						$authors[$i][] = $o;
						$all[] = $o;
					}
				}
			}
		}

	}
	return $authors;
}
//select best name out of array with same authors
function get_best_name($authorslist){
	$authorslist = remove_element($authorslist, '%');
	$authorslist = remove_element($authorslist, '_',1);
	$authorslist = remove_element($authorslist, '_',2);
	$authorslist = remove_element($authorslist, '\.',2);
	
    $mapping = array_combine($authorslist, array_map('strlen', $authorslist));
    $value = array_keys($mapping, max($mapping));
	return $value[0];
}

//remove with heuristics from get_best_name
function remove_element($arr, $val, $pos=0){
	foreach ($arr as $key => $value){
		if($pos == 0){
			if (preg_match('/'.$val.'/',$arr[$key])){
				unset($arr[$key]);
			}
		}
		if($pos == 1){
			$url = explode('/',$arr[$key]);
			if (preg_match('/^'.$val.'/',$url[4])){
				$url[4] = substr($url[4],1);
				$arr[$key] = $url[0].$url[1].$url[2].$url[3].$url[4];
			}
		}
		if($pos == 2){
			$url = explode('/',$arr[$key]);
					
			if (preg_match('/'.$val.'$/',$url[4])){
				$url[4] = substr($url[4], 0, -1);
				$arr[$key] = $url[0].$url[1].$url[2].$url[3].$url[4];
			}
		}
	}
	return $arr = array_values($arr);
}

// rewrite the authors to the best choice
function rewrite($authors){
	foreach($authors as $authorlist){
		foreach($authorlist as $author){
			$url = explode('/',$author);
			$url = str_replace('_',' ',urldecode($url[4]));
			$replace = explode('/',get_best_name($authorlist));
			$replace = str_replace('_',' ',urldecode($replace[4]));

			mysql_query("UPDATE authors_dn SET name = '".$replace."' WHERE name = '".$url."'");
			//echo '<pre>'; print_r($authorlist); echo '</pre>';
			//print 'Rewrite to: '.get_best_name($authorlist);
		}
	}
}

function print_authors($authors){
	echo '<pre>';
	print_r($authors);
	echo '</pre>';
}

//denormalize();
parse_sames();
$authors = bundle_authors();
print_authors($authors);
rewrite($authors);



?>
